<!--
 * @Author: your name
 * @Date: 2021-03-15 20:53:56
 * @LastEditTime: 2021-03-15 20:56:17
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edi
 * @FilePath: \study\js\面试题\数组计算.html
-->
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>

    <body>
        <p>数组扁平化</p>
        <script>
            let ary = [1, [2, 22, [3, 33, [4, 5, 55]]], 6, 66];
            let str = JSON.stringify(ary);
            console.warn(ary);
            console.warn(str);

            console.warn(` \n1  ary.flat(Infinity)`);
            console.log(ary.flat(Infinity));
            console.log(ary);

            console.warn(` \n2  str.replace(/\[|\]/g, '').split(',') `);
            console.log(str.replace(/\[|\]/g, '').split(','));
            console.log(str.replace(/(\[\]\,)|[\[\]]*/g, '').split(','));

            // 第三种处理：递归处理
            console.warn(` \n3  递归处理 `);
            function dg(arr) {
                console.log('-------dg----------', JSON.stringify(arr));
                let list = [];
                arr.forEach((item) => {
                    console.log(item);
                    if (Array.isArray(item)) {
                        list = [...list, ...dg(item)];
                    } else {
                        list.push(item);
                    }
                });
                console.log('--->', list);
                return list;
            }
            console.log(dg(ary));

            console.warn(` \n3  用 reduce 实现数组的 flat 方法 `);
            function reduceDG(arr) {
                return arr.reduce((pre, cur) => {
                    console.log('-------reduce----------', pre, JSON.stringify(cur));
                    let item = Array.isArray(cur) ? reduceDG(cur) : cur;
                    return pre.concat(item);
                }, []);
            }
            console.log(reduceDG(ary));

            console.warn(` \n3  第五种处理：扩展运算符 `);
            function whilesome(arr) {
                // some 只要有一项是数组 就执行
                while (arr.some(Array.isArray)) {
                    console.log('------while-------', JSON.stringify(arr));
                    arr = [].concat(...arr);
                }
                return arr;
            }
            console.log(whilesome(ary));

        </script>
    </body>
</html>
